package com.ttdevs.es.service;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;

import com.ttdevs.util.BaseClass;
import com.ttdevs.util.StaticConstants;

public class MainSMSManager extends BaseClass {

	private SMSContentObserver smsContentObserver;

	public MainSMSManager(Context context, Handler handler) {
		super(context, handler);
		this.smsContentObserver = new SMSContentObserver(handler);
	}

	public void registerContentObserver() {
		if (getSPU().getSMS()) {
			getContext().getContentResolver().registerContentObserver(Uri.parse(SMSURI), true, smsContentObserver);
		}
	}

	public void unregisterContentObserver() {
		if (getSPU().getSMS()) {
			getContext().getContentResolver().unregisterContentObserver(smsContentObserver);
		}
	}

	private class SMSContentObserver extends ContentObserver implements StaticConstants {

		private static final String ID = "_id";
		private static final String DATE = "date";
		private static final String BODY = "body";

		public SMSContentObserver(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);

			Uri smsUri = Uri.parse(SMSURIINBOX);
			String[] projection = new String[] { ID, DATE, BODY }; // TODO
			Cursor cursor = getContext().getContentResolver().query(smsUri, projection, null, null, " date desc");
			if (cursor != null) {
				if (cursor.moveToFirst()) {
					String body = cursor.getString(cursor.getColumnIndex(BODY));

					String triggerMessageContent = getSPU().getAlarmSMS();
					if (body != null && body.equals(triggerMessageContent)) {
						sendAlarmMessage(SMS);
					}
				}
				cursor.close();
			}
		}
	}
}
